package org.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.entity.Audit;
import org.example.entity.User;
import org.example.mapper.UserMapper;
import org.example.mapper.AuditMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AuditService extends ServiceImpl<org.example.mapper.AuditMapper, Audit> {
    @Resource
    AuditMapper auditMapper;
    @Resource
    UserMapper userMapper;

//    public IPage<Audit> getAuditWithUser (Page<Audit>page){
//        List<Audit> auditList = auditMapper.selectList(null);
//        for (Audit audit : auditList)
//            if (ObjectUtil.isNotEmpty(audit.getUserId())) {
//                User user = userMapper.selectById(audit.getUserId());
//                if (ObjectUtil.isNotEmpty(user)) {
//                    audit.setGeoNames(user.getName());
//                }
//            }
//        page.setRecords(auditList);
//        return page;
//    }
    @Transactional  //注解确保整个操作是原子的，要么全部成功保存，要么全部失败回滚
    public IPage<Audit> getAuditWithUser (Page<Audit>page, QueryWrapper<Audit> queryWrapper){
        IPage<Audit> resultPage=auditMapper.selectPage(page,queryWrapper);
        List<Audit> auditList = resultPage.getRecords();
        for (Audit audit : auditList)
            if (ObjectUtil.isNotEmpty(audit.getUserId())) {
                User user = userMapper.selectById(audit.getUserId());
                if (ObjectUtil.isNotEmpty(user)) {
                    audit.setUsername(user.getUsername());
                    audit.setName(user.getName());
                    audit.setPhone(user.getPhone());
                    audit.setEmail(user.getEmail());
                    audit.setAvatar(user.getAvatar());
                    auditMapper.updateById(audit);
                }
            }
        return resultPage;
    }

    public List<Audit> getByUserId(Integer userId) {
        QueryWrapper<Audit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId); // 假设关联表中用户ID的字段名为 user_id
        return auditMapper.selectList(queryWrapper);
    }
}
